<template>
  <div class="call-container" v-if="showCall">
    <div class="call-header">
      <div class="call-title">
        {{ callType == 'video' ? '视频通话' : '语音通话' }} - {{ callWith }}
      </div>
      <div class="call-duration">{{ formatDuration(callDuration) }}</div>
    </div>

    <div class="video-container" v-if="callType == 'video'">
      <video ref="localVideo" autoplay muted class="local-video"></video>
      <video ref="remoteVideo" autoplay class="remote-video"></video>
    </div>
    <div v-else class="audio-container">
      <div class="audio-icon">
        <el-icon :size="80"><Microphone /></el-icon>
      </div>
      <div class="audio-name">{{ callWith }}</div>
    </div>

    <div class="call-controls">
      <el-button type="danger" circle size="large" @click="endCall">
        <el-icon><PhoneFilled /></el-icon>
      </el-button>

      <el-button v-if="callType == 'video'" type="info" circle size="large" @click="toggleVideo">
        <el-icon>
          <VideoCamera v-if="videoEnabled" />
          <VideoPause v-else />
        </el-icon>
      </el-button>

      <el-button type="info" circle size="large" @click="toggleAudio">
        <el-icon>
          <Microphone v-if="audioEnabled" />
          <Mute v-else />
        </el-icon>
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, defineExpose } from 'vue'
import {
  PhoneFilled,
  VideoCamera,
  VideoPause,
  Microphone,
  Mute
} from '@element-plus/icons-vue'

const props = defineProps({
  showCall: Boolean,
  callType: String,
  callWith: String,
  isCaller: Boolean
})

const emit = defineEmits(['end-call', 'send-signal'])

// WebRTC相关
const localVideo = ref(null)
const remoteVideo = ref(null)
const peerConnection = ref(null)
const localStream = ref(null)
const callDuration = ref(0)
const videoEnabled = ref(true)
const audioEnabled = ref(true)
let durationInterval = null

// 方法
const formatDuration = (seconds) => {
  const mins = Math.floor(seconds / 60)
  const secs = seconds % 60
  return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

// 初始化通话
const startCall = async () => {
  try {
    // 清理旧流
    if (localStream.value) {
      localStream.value.getTracks().forEach(track => track.stop())
      localStream.value = null
    }

    // 获取媒体设备
    localStream.value = await navigator.mediaDevices.getUserMedia({
      video: props.callType === 'video',
      audio: true
    })

    if (localVideo.value && props.callType === 'video') {
      localVideo.value.srcObject = localStream.value
    }

    // 创建RTCPeerConnection
    const configuration = {
      iceServers: [{ urls: 'stun:stun.l.google.com:19302' }]
    }
    peerConnection.value = new RTCPeerConnection(configuration)

    // 添加本地流
    localStream.value.getTracks().forEach(track => {
      peerConnection.value.addTrack(track, localStream.value)
    })

    // ICE候选处理
    peerConnection.value.onicecandidate = (event) => {
      if (event.candidate) {
        emit('send-signal', {
          type: 'ice-candidate',
          candidate: event.candidate
        })
      }
    }

    // 远程流处理
    peerConnection.value.ontrack = (event) => {
      if (remoteVideo.value) {
        remoteVideo.value.srcObject = event.streams[0]
      }

      // 监听远程流结束
      event.streams[0].getTracks().forEach(track => {
        track.onended = () => {
          endCall()
        }
      })

      // 开始计时器
      if (!durationInterval) {
        durationInterval = setInterval(() => {
          callDuration.value++
        }, 1000)
      }
    }

    // 如果是呼叫方，创建offer
    if (props.isCaller) {
      const offer = await peerConnection.value.createOffer()
      await peerConnection.value.setLocalDescription(offer)
      emit('send-signal', {
        type: 'offer',
        sdp: offer
      })

      // 手动启动计时器
      if (!durationInterval) {
        durationInterval = setInterval(() => {
          callDuration.value++
        }, 1000)
      }
    }

  } catch (error) {
    console.error('Call setup failed:', error)
    endCall()
  }
}

// 处理远程 Offer
const handleRemoteOffer = async (offer) => {
  if (!peerConnection.value) return

  try {
    await peerConnection.value.setRemoteDescription(new RTCSessionDescription(offer))
    const answer = await peerConnection.value.createAnswer()
    await peerConnection.value.setLocalDescription(answer)
    emit('send-signal', {
      type: 'answer',
      sdp: answer
    })
  } catch (e) {
    console.error('Error handling remote offer:', e)
  }
}

// 处理远程 Answer
const handleRemoteAnswer = async (answer) => {
  if (!peerConnection.value) return

  try {
    await peerConnection.value.setRemoteDescription(new RTCSessionDescription(answer))

    // 手动启动计时器
    if (!durationInterval && !props.isCaller) {
      durationInterval = setInterval(() => {
        callDuration.value++
      }, 1000)
    }
  } catch (e) {
    console.error('Error handling remote answer:', e)
  }
}

// 处理远程 ICE Candidate
const handleRemoteCandidate = async (candidate) => {
  if (!peerConnection.value) return

  try {
    await peerConnection.value.addIceCandidate(new RTCIceCandidate(candidate))
  } catch (e) {
    console.error('Error adding ICE candidate:', e)
  }
}

// 挂断
const endCall = () => {
  // 停止所有媒体轨道
  if (localStream.value) {
    localStream.value.getTracks().forEach(track => {
      track.stop()
      track.enabled = false
    })
    localStream.value = null
  }

  // 清理远端视频流
  if (remoteVideo.value && remoteVideo.value.srcObject) {
    const remoteStream = remoteVideo.value.srcObject;
    if (remoteStream instanceof MediaStream) {
      remoteStream.getTracks().forEach(track => track.stop())
    }
    remoteVideo.value.srcObject = null
    remoteVideo.value.load()
  }

  // 关闭PeerConnection
  if (peerConnection.value) {
    peerConnection.value.close()
    peerConnection.value = null
  }

  // 清除计时器
  if (durationInterval) {
    clearInterval(durationInterval)
    durationInterval = null
  }

  // 确保视频元素清空
  if (localVideo.value) {
    localVideo.value.srcObject = null
    localVideo.value.load()
  }
  if (remoteVideo.value) {
    remoteVideo.value.srcObject = null
    remoteVideo.value.load()
  }

  // 通知父组件，并传递是否主动挂断的标志
  emit('end-call', {
    duration: callDuration.value,
    isActiveEnd: true
  })

  // 强制释放媒体设备
  navigator.mediaDevices.getUserMedia({ video: false, audio: false })
    .then(stream => {
      stream.getTracks().forEach(track => track.stop())
    })
    .catch(() => {})
}

defineExpose({ startCall, handleRemoteOffer, handleRemoteAnswer, handleRemoteCandidate })

onMounted(() => {
  startCall()

  // 添加通话状态检查
  const checkInterval = setInterval(() => {
    if (!peerConnection.value || peerConnection.value.connectionState === 'disconnected') {
      endCall()
      clearInterval(checkInterval)
    }
  }, 1000)
})
</script>

<style scoped>
.call-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #000;
  z-index: 9999;
  display: flex;
  flex-direction: column;
}

.call-header {
  padding: 20px;
  color: white;
  text-align: center;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 10;
}

.call-title {
  font-weight: bold;
  font-size: 18px;
}

.call-duration {
  font-size: 14px;
  margin-top: 5px;
}

.video-container {
  flex: 1;
  position: relative;
}

.audio-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: white;
}

.audio-icon {
  margin-bottom: 20px;
}

.audio-name {
  font-size: 24px;
}

.local-video {
  position: absolute;
  bottom: 20px;
  right: 20px;
  width: 200px;
  height: 150px;
  border: 2px solid white;
  border-radius: 8px;
  object-fit: cover;
}

.remote-video {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.call-controls {
  display: flex;
  justify-content: center;
  padding: 20px;
  gap: 20px;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 10;
}
</style>